<template>
  <div>
    <div class="search-term">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
        <el-form-item label="车次">
          <el-input @keyup.native.enter="onSubmit" placeholder="搜索条件" clearable v-model="searchInfo.trainNo"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="onSubmit" type="primary">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="openDialog" type="primary">新增动车组</el-button>
        </el-form-item>
        <el-form-item>
          <el-popover placement="top" v-model="deleteVisible" width="160">
            <p>确定要删除吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button @click="deleteVisible = false" size="mini" type="text">取消</el-button>
                <el-button @click="onDelete" size="mini" type="primary">确定</el-button>
              </div>
            <el-button icon="el-icon-delete" size="mini" slot="reference" type="danger">批量删除</el-button>
          </el-popover>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="tableData"
      @selection-change="handleSelectionChange"
      border
      ref="multipleTable"
      stripe
      style="width: 100%"
      tooltip-effect="dark"
    >
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column align="center" label="车次" prop="trainNo" width="200"></el-table-column>
    <el-table-column align="center" label="硬卧" prop="trainHard" width="200"></el-table-column>
    <el-table-column align="center" label="软座" prop="trainSoft" width="200"></el-table-column>
      <el-table-column align="center" label="按钮组">
        <template slot-scope="scope">
          <el-button class="table-button" @click="updateTrain(scope.row)" size="small" type="primary" icon="el-icon-edit">变更</el-button>
          <el-button class="table-button" @click="handleDistributeTrain(scope.row)" size="small" type="success" icon="el-icon-edit">路线分配</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRow(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="page"
      :page-size="pageSize"
      :page-sizes="[10, 30, 50, 100]"
      :style="{float:'right',padding:'20px'}"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <el-dialog :before-close="closeDialog" :visible.sync="dialogFormVisible" title="弹窗操作">
      <el-form :model="formData" label-position="right" label-width="80px">
         <el-form-item label="车次:">
            <el-input v-model="formData.trainNo" clearable placeholder="请输入" ></el-input>
      </el-form-item>

         <el-form-item label="硬卧:"><el-input v-model.number="formData.trainHard" clearable placeholder="请输入"></el-input>
      </el-form-item>

         <el-form-item label="软座:"><el-input v-model.number="formData.trainSoft" clearable placeholder="请输入"></el-input>
      </el-form-item>
       </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button @click="enterDialog" type="primary">确 定</el-button>
      </div>
    </el-dialog>

    <!--路线分配弹窗-->
    <el-dialog title="路线分配" :visible.sync="distributeDialogVisible">
      <div style="width: 800px; height: 300px">
        <div style="float: left; width: 460px; height: 100px;">
          <el-table
                  :data="allLinesList"
                  @selection-change="handleAddLinesTrainSelectionChange"
                  border
                  ref="table"
                  stripe
                  style="width: 100%; margin-left: 40px"
                  tooltip-effect="dark"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="路线始终点" align="center" prop="line_name" ></el-table-column>
          </el-table>
        </div>
        <el-button style="margin-left: 60px" @click="doSave" type="primary" size="normal">保存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
    createTrain,
    deleteTrain,
    deleteTrainByIds,
    updateTrain,
    findTrain,
    getTrainList,
    addTrainLines
} from "@/api/train";  //  此处请自行替换地址
import { formatTimeToStr } from "@/utils/date";
import infoList from "@/mixins/infoList";
import {getLinesList} from "@/api/lines";
export default {
  name: "Train",
  mixins: [infoList],
  data() {
    return {
      shouldSelectedList:[],//已经选择的id组成的数组
      rowTrainId: '', // 当前行车ID
      checkedArr: [], // 复选框选中的数据数组
      allLinesList: [], // 所有路线
      linesArray: [], // 已拥有的路线
      distributeDialogVisible: false,
      listApi: getTrainList,
      dialogFormVisible: false,
      type: "",
      deleteVisible: false,
      multipleSelection: [],
      formData: {
            trainNo:"",
            trainHard: 100,
            trainSoft: 120,
      }
    };
  },
  methods: {
    // 监听复选框选项集合
    handleAddLinesTrainSelectionChange(data) {
      this.checkedArr = data // 保存选中的数据数组
      console.log('选中的数据数组')
      console.log(this.checkedArr)
    },
    // 分配路线控制
    handleDistributeTrain(row) {
      console.log('当前行数据')
      console.log(row)
      this.rowTrainId = row.ID // 保存当前行ID
      findTrain({ ID: row.ID }).then(res => {
        this.type = "update";
          this.formData = res.data.retrain
          this.linesArray = res.data.retrain.lines
          this.distributeDialogVisible = true
          // 取出结果集合中的每一项的ID
          for (let i in res.data.retrain.lines) {
            this.shouldSelectedList.push(res.data.retrain.lines[i].ID)
            console.log('查询到的需要选中路线的ID集合数组')
            console.log(this.shouldSelectedList)
            // 设置el-table中复选框默认选中
            this.$nextTick(() => {
              this.allLinesList.forEach(row => {
                if (this.shouldSelectedList.indexOf(row.ID) >= 0) {
                  this.$refs.table.toggleRowSelection(row, true);
                }
              })
            })
          }
      })
    },
    // 获取所有路线
    getLinesList() {
      getLinesList().then(response => {
        this.allLinesList = response.data.list
      })
    },
    // 点击保存按钮时处理
    async doSave() {
      console.log('提交选中的数组')
      console.log(this.checkedArr)
      console.log('提交的行ID')
      console.log(this.rowTrainId)
      const res = await addTrainLines({
        lines: this.checkedArr,
        trainId: this.rowTrainId
      })
        console.log('返回结果')
        console.log(res)
        if (res.code === 0) {
          // 更新获取所有路线
          this.getLinesList()
          this.$message.success('设置路线成功')
          this.distributeDialogVisible = false
          this.shouldSelectedList = []
        }
    },

      //条件搜索前端看此方法
    onSubmit() {
        this.page = 1
        this.pageSize = 10
        this.getTableData()
      },
    handleSelectionChange(val) {
        this.multipleSelection = val
      },
    // 删除行
    deleteRow(row){
        this.$confirm('确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           this.deleteTrain(row);
        });
      },
    async onDelete() {
        const ids = []
        if(this.multipleSelection.length == 0){
          this.$message({
            type: 'warning',
            message: '请选择要删除的数据'
          })
          return
        }
        this.multipleSelection &&
          this.multipleSelection.map(item => {
            ids.push(item.ID)
          })
        const res = await deleteTrainByIds({ ids })
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          if (this.tableData.length == ids.length) {
              this.page--;
          }
          this.deleteVisible = false
          this.getTableData()
        }
      },
    async updateTrain(row) {
      const res = await findTrain({ ID: row.ID });
      console.log(res)
      this.type = "update";
      if (res.code == 0) {
        this.formData = res.data.retrain;
        this.dialogFormVisible = true;
      }
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.formData = {
          trainNo:"",
          trainHard:0,
          trainSoft:0,

      };
    },
    async deleteTrain(row) {
      const res = await deleteTrain({ ID: row.ID });
      if (res.code == 0) {
        this.$message({
          type: "success",
          message: "删除成功"
        });
        if (this.tableData.length == 1) {
            this.page--;
        }
        this.getTableData();
      }
    },
    async enterDialog() {
      let res;
      switch (this.type) {
        case "create":
          res = await createTrain(this.formData);
          break;
        case "update":
          res = await updateTrain(this.formData);
          break;
        default:
          res = await createTrain(this.formData);
          break;
      }
      if (res.code == 0) {
        this.$message({
          type:"success",
          message:"创建/更改成功"
        })
        this.closeDialog();
        this.getTableData();
      }
    },
    openDialog() {
      this.type = "create";
      this.dialogFormVisible = true;
    }
  },
  filters: {
    formatDate: function(time) {
      if (time != null && time != "") {
        var date = new Date(time);
        return formatTimeToStr(date, "yyyy-MM-dd hh:mm:ss");
      } else {
        return "";
      }
    },
    formatBoolean: function(bool) {
      if (bool != null) {
        return bool ? "是" :"否";
      } else {
        return "";
      }
    }
  },
  created() {
    this.getTableData()
    this.getLinesList()
 }
};
</script>

<style>
</style>
